<?php

namespace App\Exceptions;

use App\Library\Logic\SqlErrorLogic;
use App\Library\MySeasLog;
use Error;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use TypeError;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var string[]
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var string[]
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e): array|Response|JsonResponse|\Symfony\Component\HttpFoundation\Response
    {
        if ($request->input('syp_viki')) {
            return parent::render($request, $e);
        } else if ($e instanceof ValidationException) {
            $errors = $e->validator->errors()->toArray();
            if (count($errors)) {
                MySeasLog::error($errors);
                return failCodeMessage(422, $errors[array_keys($errors)[0]][0]);
            }
        } else if ($e instanceof QueryException) {
            $message = $e->getMessage();
            MySeasLog::error([423, $message]);
            if (!prod()) return failCodeMessage(423, $message);
            else return failMessage('请求频繁:' . $this->sqlError((string)$e->getCode(), $message));
        } else if ($e instanceof ModelNotFoundException) {
            $message = $e->getMessage();
            MySeasLog::error([424, $message]);
            return failCodeMessage(424, $message);
        } else if ($e instanceof NotFoundHttpException) {
            MySeasLog::error([404, '找不到页面']);
            return fail(404);
        } else if ($e instanceof Exception) {
            $message = $e->getMessage();
            if ($request->input('syp_viki')) {
                MySeasLog::error([499, $message]);
                return failCodeMessage(499, $message);
            }
            MySeasLog::error([$message]);
            return failMessage($message);
        } else if ($e instanceof TypeError) {
            $message = $e->getMessage();
            MySeasLog::error(['TypeError', $message]);
            return failMessage($message);
        } else if ($e instanceof Error) {
            $message = $e->getMessage();
            MySeasLog::error(['Error', $message]);
            return failMessage($message);
        }
        return parent::render($request, $e);
    }

    /**
     *
     * @param string $code
     * @param string $message
     * @return int
     * @throws Exception
     *
     */
    private function sqlError(string $code, string $message): int
    {
        $sqlError = SqlErrorLogic::insertForModel(['code' => $code, 'message' => $message]);
        wechatTemplate('sqlError', $sqlError->serial_number);
        return $sqlError->id;
    }
}
